<!-- 页面 -->
<template>
  <su-popup :show="show" round="10" @close="onClosePoster" type="center" class="popup-box">
    <view class="ss-flex-col ss-col-center ss-row-center">
      <view v-if="poster.src === ''" class="poster-title ss-flex ss-row-center" :style="{
        height: poster.height + 'px',
        width: poster.width + 'px',
      }">
        海报加载中...
      </view>
      <image v-else class="poster-img" :src="poster.src" :style="{
        height: poster.height + 'px',
        width: poster.width + 'px',
      }"></image>
      <canvas class="hideCanvas" :canvas-id="poster.canvasId" :id="poster.canvasId" :style="{
        height: poster.height + 'px',
        width: poster.width + 'px',
      }" />
      <view class="poster-btn-box ss-m-t-20 ss-flex ss-row-between ss-col-center" v-if="poster.src != ''">
        <button class="cancel-btn ss-reset-button" @tap="onClosePoster">取消</button>
        <button class="save-btn ss-reset-button ui-BG-Main" @tap="onSavePoster">
          {{
            ['wechatOfficialAccount', 'H5'].includes(sheep.$platform.name)
            ? '长按图片保存'
            : '保存图片'
          }}
        </button>
      </view>
    </view>
  </su-popup>
</template>

<script setup>
import { reactive, getCurrentInstance, ref } from 'vue';
import sheep from '@/sheep';
// import useCanvas from './useCanvas';

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  shareInfo: {
    type: Object,
    default() { },
  },
});

const poster = reactive({
  canvasId: 'canvasId',
  width: sheep.$platform.device.windowWidth * 0.9,
  height: 600,
  src: '',
});

const emits = defineEmits(['success', 'close']);
const vm = getCurrentInstance();
const posterUrl = ref('')
const onClosePoster = () => {
  emits('close');
};

const onSavePoster = () => {
  // H5和公众号保持原有逻辑
  if (['WechatOfficialAccount', 'H5'].includes(sheep.$platform.name)) {
    sheep.$helper.toast('请长按图片保存');
    return;
  }

  // 小程序环境下，先检查授权
  // #ifdef MP
  uni.getSetting({
    success: (res) => {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        uni.authorize({
          scope: 'scope.writePhotosAlbum',
          success: () => {
            downloadAndSave();
          },
          fail: () => {
            uni.showModal({
              title: '提示',
              content: '需要您授权保存图片到相册',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting({
                    success: (settingRes) => {
                      if (settingRes.authSetting['scope.writePhotosAlbum']) {
                        downloadAndSave();
                      } else {
                        sheep.$helper.toast('获取权限失败，无法保存图片');
                      }
                    }
                  });
                }
              }
            });
          }
        });
      } else {
        downloadAndSave();
      }
    }
  });
  // #endif

  // #ifndef MP
  downloadAndSave();
  // #endif
};

const downloadAndSave = () => {
  uni.showLoading({
    title: '正在保存...'
  });

  uni.downloadFile({
    url: posterUrl.value,
    success: (sres) => {
      uni.saveImageToPhotosAlbum({
        filePath: sres.tempFilePath,
        success: () => {
          uni.hideLoading();
          onClosePoster();
          sheep.$helper.toast('保存成功');
        },
        fail: (err) => {
          uni.hideLoading();
          sheep.$helper.toast('保存失败');
          console.log('图片保存失败:', err);
        }
      });
    },
    fail: (err) => {
      uni.hideLoading();
      sheep.$helper.toast('下载图片失败');
      console.log('下载失败:', err);
    }
  });
};

async function getPoster(params) {
  poster.src = '';

console.log('shareInfo',props.shareInfo,spm)
  poster.shareInfo = props.shareInfo;
  var spm=poster.shareInfo.query.split('=')[1]
  var page=spm.split('.')[1]
  // #ifdef APP-PLUS
  poster.canvasId = 'canvasId-' + new Date().getTime();
  // #endif
  
  var res 
  if(page==7){//7团购商品
	  res =await sheep.$api.goods.posterGroup({
	   id: props.shareInfo.poster.id
	 })
  }else if(page==8){//鲸喜店铺
	  res =await sheep.$api.goods.posterSurpriseShop({
	    id: props.shareInfo.poster.id
	  })
  }else{
	res =await sheep.$api.goods.poster({
	   id: props.shareInfo.poster.id
	 })  
  }
 // let res = page!=7?await sheep.$api.goods.poster({//7团购   需要还接口
 //   id: props.shareInfo.poster.id
 // }):await sheep.$api.goods.posterGroup({
 //   id: props.shareInfo.poster.id
 // })
 posterUrl.value = res.data.poster_url
 poster.src = res.data.poster_url

 if (!res.error) {
   uni.showToast({
     icon: 'success',
     title: res.msg
   })
 }
  

 
}

defineExpose({
  getPoster,
});
</script>

<style lang="scss" scoped>
.popup-box {
  position: relative;
}

.poster-title {
  color: #999;
}

// 分享海报
.poster-btn-box {
  width: 600rpx;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: -80rpx;

  .cancel-btn {
    width: 240rpx;
    height: 70rpx;
    line-height: 70rpx;
    background: $white;
    border-radius: 35rpx;
    font-size: 28rpx;
    font-weight: 500;
    color: $dark-9;
  }

  .save-btn {
    width: 240rpx;
    height: 70rpx;
    line-height: 70rpx;
    border-radius: 35rpx;
    font-size: 28rpx;
    font-weight: 500;
  }
}

.poster-img {
  border-radius: 20rpx;
}

.hideCanvas {
  position: fixed;
  top: -99999rpx;
  left: -99999rpx;
  z-index: -99999;
}
</style>
